<template>
  <div class="notice-detail">

    <!-- 公告信息 -->
    <div class="title">公告信息</div>
    <div class="form">
      <!-- 标题 -->
      <div class="form-item">
        <CustomInput
          v-model="formItem.noticeTitle"
          title="标题"
          placeholder="请填写标题"
          :isInput="true" />
      </div>
      <!-- 内容 -->
      <div class="form-item">
        <CustomInput
          v-model="formItem.noticeContent"
          title="内容"
          placeholder="请填写内容"
          :isInput="true" />
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="action">
      <i-button type="primary" @click="actionClick">保存</i-button>
    </div>
  </div>
</template>

<script>
import CustomInput from 'components/CustomInput/CustomInput'
import { mapState } from 'vuex'
import { ERR_OK } from 'api/config'
import { saveData } from 'api/noticeDetail'
import { shareMixin } from 'common/js/mixins'

export default {
  mixins: [shareMixin()],
  components: {
    CustomInput
  },
  computed: {
    ...mapState({
      currentItem: state => state.noticeDetail.currentItem,
      actionKey: state => state.noticeDetail.actionKey
    })
  },
  mounted () {
    this.initData()
  },
  data () {
    return {
      formItem: {}
    }
  },
  methods: {
    initData () {
      if (this.actionKey === 'edit') {
        this.formItem = JSON.parse(JSON.stringify(this.currentItem))
      } else {
        this.formItem = {
          noticeTitle: '',
          noticeContent: ''
        }
      }
    },
    actionClick () {
      const obj = JSON.parse(JSON.stringify(this.formItem))

      this.deleteCustomKey(obj)

      if (obj['createDt']) {
        delete obj['createDt']
      }

      this.saveData(obj)
    },
    deleteCustomKey (obj) {
      for (let key in obj) {
        if (key.indexOf('__custom_') > -1 || obj[key] === null) {
          delete obj[key]
        }
      }
    },
    async saveData (data) {
      this.$showLoading('保存中')

      const res = await saveData(data)

      this.$hideLoading()

      if (res.code === ERR_OK) {
        this.$showToast({
          title: '保存成功',
          success: () => {
            wx.navigateBack()
          }
        })
      } else {
        this.$showToast({
          title: (res && res.msg) || '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .notice-detail {
    width: 100%;
    overflow-x: hidden;
    > .title {
      width: 100%;
      line-height: 40px;
      background-color: rgb(248, 248, 248);
      font-size: 14px;
      padding-left: 10px;
    }
    > .form {
      > .form-item {
        border-bottom: 1px solid rgb(238, 238, 238);
      }
    }
  }
</style>
